package ru.gelin.android.bells.timers;

import java.util.Calendar;
import java.util.Date;

/**
 *  Period of the timer, in hours and minutes.
 */
public class Period {

    /** Hours of the timer period */
    int hours;
    
    /** Minutes of the timer period */
    int minutes;
    
    /**
     *  Creates new period.
     *  @param hours    0-24
     *  @param minutes  0-59
     */
    public Period(int hours, int minutes) {
        this.hours = hours;
        this.minutes = minutes;
        if (hours * 60 + minutes <= 0) {
            this.hours = 0;
            this.minutes = 1;
        }
    }

    public int getHours() {
        return hours;
    }

    public int getMinutes() {
        return minutes;
    }
    
    /**
     *  Adds the period to the date.
     */
    public Date add(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(Timer.normalizeDate(date));
        calendar.add(Calendar.HOUR_OF_DAY, hours);
        calendar.add(Calendar.MINUTE, minutes);
        return calendar.getTime();
    }
    
    /**
     *  Subtracts the period from the date.
     */
    public Date sub(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(Timer.normalizeDate(date));
        calendar.add(Calendar.HOUR_OF_DAY, -hours);
        calendar.add(Calendar.MINUTE, -minutes);
        return calendar.getTime();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + hours;
        result = prime * result + minutes;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Period other = (Period) obj;
        if (hours != other.hours)
            return false;
        if (minutes != other.minutes)
            return false;
        return true;
    }

}
